import re
import random
from wsgiref.simple_server import make_server


def app(env, callback):
    # parse_url 函数要查找两个信息：
    # 1. 响应函数
    # 2. url中的日期参数
    params, worker = parse_url(env['PATH_INFO'])
    status, headers, body = worker(env, *params)
    callback(status, headers)
    return [body]


def show_article(env, year, month):
    year = int(year)
    month = int(month)

    if 1 <= month <= 12:
        total = random.randint(10, 20)
        body = 'Article list of %s-%s\n\n' % (year, month)
        for i in range(total):
            body += 'article %s\n' %i
        body = body.encode()
        status = '200 OK'
    else:
        body = b'NOT FOUND'
        status = '404 NOT FOUND'
    headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(body)))
    ]
    return status, headers, body


def default_worker(env):
    status = '404 NOT FOUND'
    headers = [('Content-Type', 'text/plain')]
    body = b'NOT FOUND'
    return status, headers, body


def hello(env):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain')]
    body = b'Hello world.'
    return status, headers, body


def parse_url(url):
    # re.search(r'.*/article/([0-9]{4})/([0-9]{1,2})', 'http://localhost:8000/article/2019/07')
    for pattern, worker in url_worker_mapping:
        m = re.match(pattern, url)
        if m is not None:  # 如果匹配
            params = m.groups()
            return params, worker
    # 当找不到匹配时，返回默认的响应函数
    return (), default_worker


url_worker_mapping = [
    (r'/article/([0-9]{4})/([0-9]{1,2})', show_article),
    (r'/hello', hello),
]


if __name__ == '__main__':
    host = 'localhost'
    port = 8000
    print('serving on %s:%s' % (host, port))
    httpd = make_server(host, port, app)
    httpd.serve_forever()
